package org.lc.stk.dao.course;

import java.util.List;

import org.lc.stk.model.course.KnowledgePoint;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface KnowledgePointRepository extends JpaRepository<KnowledgePoint, Integer>, JpaSpecificationExecutor<KnowledgePoint> {
    /**
     * 根据课程ID查询知识点
     */
    List<KnowledgePoint> findByCourseId(Integer courseId);

    /**
     * 根据章节ID查询知识点
     */
    List<KnowledgePoint> findByChapterId(Integer chapterId);

    /**
     * 根据课程ID和名称模糊查询知识点
     */
    Page<KnowledgePoint> findByCourseIdAndNameContaining(Integer courseId, String name, Pageable pageable);

    /**
     * 根据课程ID删除所有知识点
     */
    void deleteByCourseId(Integer courseId);

    /**
     * 根据章节ID删除所有知识点
     */
    void deleteByChapterId(Integer chapterId);

    /**
     * 检查知识点是否作为其他知识点的前置知识点
     */
    @Query("SELECT COUNT(k) > 0 FROM KnowledgePoint k JOIN k.preKnowledges p WHERE p.id = :knowledgePointId")
    boolean isPreKnowledgePoint(@Param("knowledgePointId") Integer knowledgePointId);

    /**
     * 查找指定知识点的直接前置知识点
     */
    @Query("SELECT k.preKnowledges FROM KnowledgePoint k WHERE k.id = :knowledgePointId")
    List<KnowledgePoint> findPreKnowledgePoints(@Param("knowledgePointId") Integer knowledgePointId);

    /**
     * 查找指定知识点的直接后置知识点
     */
    @Query("SELECT k.nextKnowledges FROM KnowledgePoint k WHERE k.id = :knowledgePointId")
    List<KnowledgePoint> findNextKnowledgePoints(@Param("knowledgePointId") Integer knowledgePointId);

    /**
     * 检查某个知识点是否存在于课程中
     */
    boolean existsByCourseIdAndId(Integer courseId, Integer knowledgePointId);

    /**
     * 检查某个知识点是否存在于章节中
     */
    boolean existsByChapterIdAndId(Integer chapterId, Integer knowledgePointId);
}